package com.button.file.application.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.button.file.application.conf.FileLoadProperties;
import com.button.file.application.exception.FileException;
import com.button.file.application.service.FileUploadService;

@Service
public class FileUploadServiceImpl implements FileUploadService {
	private final Path fileStorageLocation; // 文件在本地存储的地址
	@Autowired
	public FileUploadServiceImpl(FileLoadProperties fileProperties) {
		this.fileStorageLocation = Paths.get(fileProperties.getUploadDir()).toAbsolutePath().normalize();
		try {
			Files.createDirectories(this.fileStorageLocation);
		} catch (Exception ex) {
			throw new FileException("保存文件创建文件夹时出现异常.", ex);
		}
	}

	/**
	 * 存储文件到系统
	 *
	 * @param file 文件
	 * @return 文件名
	 */
	@Override
	public String storeFile(MultipartFile file) {
		String fileName = StringUtils.cleanPath(file.getOriginalFilename());
		try {
			if (fileName.contains("..")) {
				throw new FileException("抱歉，文件名包含不合法的字符." + fileName);
			}
			Path targetLocation = this.fileStorageLocation.resolve(fileName);
			Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
			return fileName;
		} catch (IOException ex) {
			throw new FileException("保存文件:" + fileName + "时出现异常,请重试!!", ex);
		}
	}
}
